package com.zyc.ui;

import com.zyc.R;
import com.zyc.misc.AlarmReceiver;
import com.zyc.misc.Constant;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.DatePicker.OnDateChangedListener;
import android.widget.TimePicker;
import android.widget.TimePicker.OnTimeChangedListener;
import android.widget.Toast;
import android.widget.ToggleButton;

import java.util.Calendar;

/**
 * @author ZengYongchang@gmail.com
 */
public class ItemSetAndLaunchActivity extends Activity{
    private ToggleButton mBtnToggleReminder;
    private DatePicker mDatePicker;
    private TimePicker mTimePicker;

    private TimeHolder mTimeHolder;
    private Calendar mCalendar;

    private Uri mUri;
    private int mRowId;

    private Intent mIntent;
    private AlarmManager mAlarmManager;    
    

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.item_set_and_launch_activity);

        mDatePicker = (DatePicker) findViewById(R.id.date_picker);
        mTimePicker = (TimePicker) findViewById(R.id.time_picker);
        mBtnToggleReminder = (ToggleButton) findViewById(R.id.btn_toggle_reminder);
        mBtnToggleReminder.setOnClickListener(new Button.OnClickListener() {
            @Override
            public void onClick(View v) {
                btnToggleReminderOnClickImpl();
            }
        });

        mUri = getIntent().getData();
        mRowId = Integer.parseInt(mUri.getPathSegments().get(1));
        
        Cursor cursor = getContentResolver().query(mUri, new String[]{ Constant.Db.EXPIRE_TIME_COLUMN }, null, null, null);
        cursor.moveToFirst();
        int columnIndex = cursor.getColumnIndex(Constant.Db.EXPIRE_TIME_COLUMN);
        Boolean isExpireTimeFieldEmpty = cursor.isNull(columnIndex);
        mBtnToggleReminder.setChecked(!isExpireTimeFieldEmpty);

        mCalendar = Calendar.getInstance();
        mCalendar.setTimeInMillis(isExpireTimeFieldEmpty ? System.currentTimeMillis() : cursor.getLong(columnIndex));
        cursor.close();
        
        mTimeHolder = new TimeHolder(mCalendar.get(Calendar.YEAR), mCalendar.get(Calendar.MONTH), mCalendar.get(Calendar.DAY_OF_MONTH), 
                                     mCalendar.get(Calendar.HOUR_OF_DAY) + Constant.DEFAULT_HOUR_INCREMENT, mCalendar.get(Calendar.MINUTE));

        mDatePicker.init(mTimeHolder.getYear(), mTimeHolder.getMonth(), mTimeHolder.getDay(), new OnDateChangedListener() {
            @Override
            public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                dateChangedImpl(year, monthOfYear, dayOfMonth);
            }
        });

        mTimePicker.setOnTimeChangedListener(new OnTimeChangedListener() {
            @Override
            public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
                timeChangedImpl(hourOfDay, minute);
            }
        });
        mTimePicker.setIs24HourView(true);
        mTimePicker.setCurrentHour(mTimeHolder.getHour());
        mTimePicker.setCurrentMinute(mTimeHolder.getMinute() + 1 );

        mIntent = new Intent(this, AlarmReceiver.class);
        mIntent.setData(mUri);
        mAlarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    }


    @Override
    public boolean onKeyDown(int keyCode, android.view.KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_L) {
            if (!mBtnToggleReminder.isChecked()) {
                LaunchCurrentReminder();
                mBtnToggleReminder.setChecked(true);
            } else {
                Toast.makeText(this, "current status is already-launched, please cancel reminder first, then do re-launch", Toast.LENGTH_LONG).show();
            }
            return true;
        } else if(keyCode == KeyEvent.KEYCODE_C) {
            if (mBtnToggleReminder.isChecked()) {
                CancelCurrentReminder();
                mBtnToggleReminder.setChecked(false);
            } else {
                Toast.makeText(this, "current status is already-canceled, please launch reminder first, then do re-cancel", Toast.LENGTH_LONG).show();
            }
            return true;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }


    private void LaunchCurrentReminder() {
        PendingIntent p_intent = PendingIntent.getBroadcast(this, mRowId, mIntent, 0);
        mCalendar.set(mTimeHolder.getYear(), mTimeHolder.getMonth(), mTimeHolder.getDay(), mTimeHolder.getHour(), mTimeHolder.getMinute());
        mAlarmManager.set(AlarmManager.RTC_WAKEUP, mCalendar.getTimeInMillis(), p_intent);

        ContentValues values = new ContentValues();
        values.put(Constant.Db.EXPIRE_TIME_COLUMN, mCalendar.getTimeInMillis());
        getContentResolver().update(mUri, values, null, null);
    }


    private void CancelCurrentReminder() {
        PendingIntent p_intent = PendingIntent.getBroadcast(this, mRowId, mIntent, 0);
        mAlarmManager.cancel(p_intent);

        ContentValues values = new ContentValues();
        values.putNull(Constant.Db.EXPIRE_TIME_COLUMN);
        getContentResolver().update(mUri, values, null, null);
    }



    private void btnToggleReminderOnClickImpl() {
        if (mBtnToggleReminder.isChecked())
            LaunchCurrentReminder();
        else
            CancelCurrentReminder();
    }

    
    private void dateChangedImpl(int year, int monthOfYear, int dayOfMonth) {
        mTimeHolder.setYear(year);
        mTimeHolder.setMonth(monthOfYear);
        mTimeHolder.setDay(dayOfMonth);
    }


    private void timeChangedImpl(int hourOfDay, int minute) {
        mTimeHolder.setHour(hourOfDay);
        mTimeHolder.setMinute(minute);
    }



    private class TimeHolder {
        private int year;
        private int month;
        private int day;
        private int hour;
        private int minute;

        public TimeHolder(int year, int month, int day, int hour, int minute) {
            this.year = year;
            this.month = month;
            this.day = day;
            this.hour = hour;
            this.minute = minute;
        }

        public int getYear() {
            return year;
        }

        public void setYear(int year) {
            this.year = year;
        }

        public int getMonth() {
            return month;
        }

        public void setMonth(int month) {
            this.month = month;
        }

        public int getDay() {
            return day;
        }

        public void setDay(int day) {
            this.day = day;
        }

        public int getHour() {
            return hour;
        }

        public void setHour(int hour) {
            this.hour = hour;
        }

        public int getMinute() {
            return minute;
        }

        public void setMinute(int minute) {
            this.minute = minute;
        }
    }
}
